let secret_code = ''
const app = getApp()
Page({
  data: {
    countDownVisible: false,
    mobile: '18888888888',
    code: ''
  },
  onLoad({
    redirectURL
  }) {
    this.setData({
      redirectURL
    })
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      // 正在倒计时
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  verifyMobile() {
    const reg = /^1[3-9]\d{9}$/
    const valid = reg.test(this.data.mobile.trim())
    if (!valid) wx.utils.toast('请填写正确的手机号码!')
    return valid
  },
  verifyCode() {
    const reg = /^\d{6}$/
    const valid = reg.test(this.data.code.trim())
    if (!valid) wx.utils.toast('请检查验证码是否正确!')
    return valid
  },
  async getCode() {
    if (!this.verifyMobile()) return
    const {
      code,
      data
    } = await wx.http.get('/code', {
      mobile: this.data.mobile.trim()
    })

    if (code !== 10000) return wx.utils.toast('发送失败，请稍后重试!')
    wx.utils.toast('发送成功, 请查收短信!')
    console.log(data.code, 'code')
    this.setData({
      countDownVisible: true
    })
    secret_code = data.code
  },
  copyCode() {
    wx.setClipboardData({
      data: secret_code
    })
  },
  async submitForm() {
    if (!this.verifyMobile()) return
    if (!this.verifyCode()) return
    const {
      mobile,
      code
    } = this.data
    const res = await wx.http.post('/login', {
      mobile,
      code
    })
    if (res.code !== 10000) return wx.utils.toast('请检查验证码是否正确!')
    app.setToken(res.data.token, res.data.refreshToken)
    wx.redirectTo({
      url: this.data.redirectURL || '/pages/index/index',
    })
  },
  goBuilding(ev) {
    wx.navigateTo({
      url: '/house_pkg/pages/building/index?point=' + ev.mark.point,
    })
  },
})